package com.example.blogsystem.utils;

import com.example.blogsystem.BlogSystemApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j

public class EmailUtils {
    private static final int CODE_LENGTH = 5;
    private static final String EMAIL_REGEX =
            "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    private static final Pattern pattern = Pattern.compile(EMAIL_REGEX);
    private static final String SEND_FROM = "smarmot@163.com";
    private static JavaMailSenderImpl javaMailSenderImpl = BlogSystemApplication.context.getBean(JavaMailSenderImpl.class);

//    @Autowired
//    public void setJavaMailSender(JavaMailSenderImpl javaMailSenderImpl) {
//        EmailUtils.javaMailSenderImpl = javaMailSenderImpl;
//    }

    //随机生成验证码
    private static String generateRandomCode() {
        String digits = "0123456789";
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();

        // 生成指定长度的随机数字验证码
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(digits.length());
            codeBuilder.append(digits.charAt(index));
        }

        return codeBuilder.toString();
    }

    public static String sendCode(String email) {
        //1.校验邮箱格式
        if(!isValidEmail(email)){
            return null;
        }
        //2.随机生成验证码
        String captcha = generateRandomCode();
        //log.info("验证码生成成功：captcha:{}", captcha);
        //3.发送验证码
        long begin = System.currentTimeMillis();
        send(captcha, email);
        long end = System.currentTimeMillis();
        log.info("邮件发送成功！耗时: {}ms", end - begin);
        //4.将验证码返回
        return captcha;
    }

    private static boolean send(String code, String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("博客系统验证码邮件");
        simpleMailMessage.setText("验证码: " + code);
        simpleMailMessage.setFrom(SEND_FROM);
        simpleMailMessage.setTo(email);
        log.info("javaMailSenderImpl.host : " + javaMailSenderImpl.getHost() + " , javaMailSenderImpl.port : " + javaMailSenderImpl.getPort());

        try {
            javaMailSenderImpl.send(simpleMailMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    public static boolean isValidEmail(String email) {
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
